package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/utils/captcha"
	"goweb/models"
	"strconv"
	"time"
)

var cpt *captcha.Captcha

func init() {
	store := cache.NewMemoryCache()
	cpt = captcha.NewWithFilter("/captcha/", store)
	cpt.ChallengeNums = 4
	cpt.StdWidth = 100
	cpt.StdHeight = 40
}

type RegisterController struct {
	CommonController
}

func (this *RegisterController) Login() {
	this.TplName = "login/login.html"
}

/**
登陆
*/
func (this *RegisterController) Checklogin() {
	resp := make(map[string]interface{})
	resp["errno"] = 1
	defer this.RetData(resp)

	if !cpt.VerifyReq(this.Ctx.Request) {
		resp["errno"] = 0
		resp["errmsg"] = "验证码错误"
		return
	}
	param := this.Ctx.Request.Form
	o := orm.NewOrm()
	userInfo := models.User{}
	userInfo.Name = param["username"][0]
	err := o.Read(&userInfo, "Name")

	if err != nil {
		resp["errno"] = 0
		resp["errmsg"] = err
		return
	}

	if userInfo.Password_hash != param["password"][0] {
		resp["errno"] = 0
		resp["errmsg"] = "用户密码错误"
		return
	}

	redis_cnn, err := cache.NewCache("redis", `{"key":"goweb","conn":"127.0.0.1:6379","dbNum":"1"}`)

	json_str, _ := json.Marshal(userInfo)
	errinfo := redis_cnn.Put(strconv.Itoa(userInfo.Id), json_str, time.Second*60)
	if errinfo == nil {
		fmt.Println(123123231)
		resp["errmsg"] = "登陆成功"
		resp["data"] = userInfo
		return
	}

	fmt.Println(456465465)
}

/**
 *用户注册
 */
func (this *RegisterController) Register() {
	param := make(map[string]interface{})
	resp := make(map[string]interface{})
	json.Unmarshal(this.Ctx.Input.RequestBody, &param)

	defer this.RetData(resp)
	o := orm.NewOrm()
	user := models.User{}
	user.Name = param["username"].(string)
	user.Password_hash = param["password"].(string)
	user.Mobile = param["username"].(string)

	id, err := o.Insert(&user)
	if err != nil {
		resp["errno"] = models.RECODE_DBERR
		resp["errmsg"] = models.RecodeText(models.RECODE_DBERR)
		resp["msg"] = err
		return
	} else {
		uinfo := make(map[string]interface{})
		uinfo["id"] = id
		uinfo["name"] = param["username"]

		resp["errno"] = models.RECODE_OK
		resp["errmsg"] = models.RecodeText(models.RECODE_OK)
		this.SetSession("uinfo", uinfo)
		return
	}
}
